package modele;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class PluginFinder implements ActionListener {

	private static final int refresh_Interval_ms = 1000;
	protected final File directory;
	protected final List<PluginEventListener> listeners = new ArrayList<PluginEventListener>();
	protected final ConfigurableTimer timer;
	protected Set<File> knownFiles = new HashSet<File>();
	protected PluginFilter filter = new PluginFilter();

	public PluginFinder(File d) {
		super();
		this.directory = d;
		this.timer = new ConfigurableTimer(this);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		Set<File> currentFiles = listFiles();
		Set<File> newFiles = new HashSet<File>(currentFiles);
		newFiles.removeAll(knownFiles);
		// System.out.println(currentFiles + " - " + knownFiles);
		for (File file : newFiles) {
			notifyListeners(file);
		}
		knownFiles = currentFiles;
	}

	/**
	 * List all files accepted by the given filter.
	 * 
	 * @return current files accepted in the directory
	 */
	public Set<File> listFiles() {
		return new HashSet<File>(Arrays.asList(directory.listFiles(filter)));
	}

	/**
	 * Notify listeners that given file have been added to the list.
	 * 
	 * @param file
	 *            which have been added
	 */
	protected void notifyListeners(File file) {
		ArrayList<PluginEventListener> listenersCopy;
		listenersCopy = new ArrayList<PluginEventListener>(listeners);
		for (PluginEventListener lis : listenersCopy) {
			lis.pluginAdded(new PluginAddedEvent(file));
		}
	}

	/**
	 * Start the timer
	 */
	public void start() {
		timer.start(refresh_Interval_ms);
	}

	public synchronized void addListener(PluginEventListener l) {
		listeners.add(l);
	}

}
